package part8forkJoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

public class ForkJoinWorkDemo {

    // forkjoin这个框架针对的是大任务执行，效率才会明显的看出来有提升，于是我把总数调大到20亿。
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test3();
    }

    /**
     * ForkJoin实现
     * invoke = 2000000001000000000 time: 8417
     */
    public static void test() throws ExecutionException, InterruptedException {
        long l = System.currentTimeMillis();

        // 实现ForkJoin 就必须有ForkJoinPool的支持
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        // 参数为起始值与结束值
        ForkJoinTask<Long> task = new ForkJoinWork(0L, 2000000000L);

        ForkJoinTask<Long> result = forkJoinPool.submit(task);
        Long aLong = result.get();

        long l1 = System.currentTimeMillis();
        System.out.println("invoke = " + aLong + " time: " + (l1 - l));
    }

    /**
     * for循环实现
     * invoke = 2000000001000000000 time: 13556
     */
    public static void test2() {
        // 普通线程实现
        Long x = 0L;
        Long y = 2000000000L;

        long l = System.currentTimeMillis();
        for (Long i = 0L; i <= y; i++) {
            x += i;
        }
        long l1 = System.currentTimeMillis();

        System.out.println("invoke = " + x + " time: " + (l1 - l));

    }


    /**
     * Java 8 并行流的实现
     * invoke = 2000000001000000000 time: 386
     */
    public static void test3() {
        long l = System.currentTimeMillis();
        long reduce = LongStream.rangeClosed(0, 2000000000L).parallel().reduce(0, Long::sum);
        long l1 = System.currentTimeMillis();
        System.out.println("invoke = " + reduce + " time: " + (l1 - l));
    }
}
